package com.firstclass.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.firstclass.entity.UserEntity;
import com.firstclass.service.UserService;
import com.firstclass.utils.FastJsonUtils;
import com.firstclass.utils.R;
import com.firstclass.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import java.awt.image.BufferedImage;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;

@Slf4j
@RestController
@RequestMapping("/back/user/")
public class UserController {
    @Autowired
    private UserService userService;

    @Resource
    DefaultKaptcha defaultKaptcha;



    @GetMapping("login")
    public String login(@RequestParam("username") String username,@RequestParam("password") String password,@RequestParam("tryCode") String tryCode, HttpServletRequest request, HttpServletResponse response) {
        String rightCode = (String) request.getSession().getAttribute("rightCode");
        if (!tryCode.equals(rightCode)) {
            return R.error("验证码错误");
        }
        if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
            return R.error("用户名或者密码为空");
        }
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("password", password);
        UserEntity userEntity = userService.getOne(wrapper);
        if (userEntity == null) {
            return R.error("jiang");
        }
        String token = TokenUtils.generateToken(userEntity.getId() + "");
        return R.ok(token);
    }




//    @PostMapping("login")
//    public String login(@RequestBody String body, HttpServletRequest request) {
//        String rightCode = (String) request.getSession().getAttribute("rightCode");
//        String tryCode = FastJsonUtils.parseObject(body, "tryCode", String.class);
//        if (!tryCode.equals(rightCode)) {
//            return R.error("验证码错误");
//        }
//        UserEntity user = FastJsonUtils.parseObject(body, "user", UserEntity.class);
//        if (StrUtil.isEmpty(user.getUsername()) || StrUtil.isEmpty(user.getPassword())) {
//            return R.error("用户名或者密码为空");
//        }
//        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
//        wrapper.eq("username", user.getUsername());
//        wrapper.eq("password", user.getPassword());
//        UserEntity userEntity = userService.getOne(wrapper);
//        if (userEntity == null) {
//            return R.error("用户名或者密码错误");
//        }
//        String token = TokenUtils.generateToken(user.getId() + "");
//        return R.ok(token);
//    }
//


//    @GetMapping("login")
//    public String login(@PathVariable("username") String username,@PathVariable("password") String password,@PathVariable("tryCode") String tryCode, HttpServletRequest request, HttpServletResponse response) {
//        String rightCode = (String) request.getSession().getAttribute("rightCode");
//        log.warn("sessionId: {}", request.getSession().getId());
//        log.warn("正确的验证码: {}", rightCode);
//        if (StrUtil.isEmpty(tryCode)) {
//            return R.error("验证码为空");
//        }
//        if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
//            return R.error("用户名或者密码为空");
//        }
//        if (userService.getName(username) == null) {
//            return R.error("用户不存在");
//        }
//        if (!tryCode.equals(rightCode)) {
//            return R.error("验证码错误");
//        }
//        if (password.equals(userService.queryPasswdByName(username))) {
//            return R.ok(JwtUtil.getToken());
//        } else {
//            return R.error("不能登录, 请重新操作");
//        }
//
//    }



    @PostMapping("register")
    public String register(@RequestBody UserEntity userEntity) {
        if (StrUtil.isBlank(userEntity.getUsername()) || StrUtil.isBlank(userEntity.getPassword())) {
            return R.error("用户名或密码为空");
        }
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userEntity.getUsername());
        if (!userService.list(wrapper).isEmpty()) {
            return R.error("用户名已经存在");
        }
        userService.save(userEntity);
        return R.ok();
    }

    @GetMapping("getPW")
    public void getKapcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        byte[] captcha = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            // 将生成的验证码保存在session
            String createText = defaultKaptcha.createText();
            request.getSession().setAttribute("rightCode", createText);
            BufferedImage bi = defaultKaptcha.createImage(createText);
            ImageIO.write(bi, "jpg", out);
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }

        captcha = out.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream sout = response.getOutputStream();
        sout.write(captcha);
        sout.flush();
        sout.close();
    }


}
